package hua.mtreader.feature.login.model;

import android.os.Build;
import android.util.Log;

import com.google.gson.Gson;

import java.io.IOException;

import hua.mtreader.common.utils.Constant;
import hua.mtreader.feature.login.bean.LoginRequestParam;
import hua.mtreader.feature.login.bean.UserBean;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/3/15.
 */

public class LoginModelImpl implements ILoginModel {

    private String TAG = getClass().getSimpleName();

    private OkHttpClient client;

    public LoginModelImpl() {
        client = new OkHttpClient();
    }

    @Override
    public void login(LoginRequestParam param, final LoginListener listener) {
        final String logUrl = Constant.root_url + "/accounts/login?";

        RequestBody formBody = new FormBody.Builder()
                .add(param.getEmail().first, param.getEmail().second)
                .add(param.getPassword().first,param.getPassword().second)
                .add(param.getDeviceId().first,param.getDeviceId().second)
                .add(param.getUa().first,param.getUa().second)
                .build();
        Request request = new Request.Builder()
                .url(logUrl)
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String json = response.body().string();
                Gson gson = new Gson();
                UserBean user = gson.fromJson(json, UserBean.class);
                listener.loginSuccess(user);

                Log.e(TAG, "2 onResponse: " + user);
            }
        });
    }



}
